package cn.ydw.community.controller;


import cn.ydw.community.entity.*;
import cn.ydw.community.event.EventProducer;
import cn.ydw.community.service.CommentService;
import cn.ydw.community.service.DiscussPostService;
import cn.ydw.community.service.LikeService;
import cn.ydw.community.service.UserService;
import cn.ydw.community.util.CommonUtils;
import cn.ydw.community.util.CommunityConstant;
import cn.ydw.community.util.HostHolder;
import cn.ydw.community.util.RedisKeyUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.ZoneId;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author dw
 * @since 2020-10-18
 */
@Controller
@RequestMapping("/discuss-post")
@Slf4j
public class DiscussPostController implements CommunityConstant {
    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;
    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/add")
    public @ResponseBody
    String addDiscussPost(String title, String content) {
        User user = hostHolder.getUser();
        if (user == null) {
            return CommonUtils.getJSON(403, "你还没有登录哦!");
        }
        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId().toString());
        post.setTitle(title);
        post.setContent(content);
        post.setStatus(0);
        post.setType(0);
        post.setCreateTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        discussPostService.addDiscussPost(post);
        // 添加帖子时触发发布事件
        Event event = new Event()
                .setUserId(user.getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setTopic(TOPIC_PUBLISH)
                .setEntityId(post.getId());
        eventProducer.fireEvent(event);
        // 计算帖子的分数
        String postScoreKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(postScoreKey, post.getId());

        // 报错的情况,将来统一处理.
        return CommonUtils.getJSON(0, "发布成功!");
    }

    @GetMapping("/detail/{discussPostId}")
    public String getDiscussion(@PathVariable("discussPostId") Integer discussPostId, Model model, Page page) {
        // 帖子
        DiscussPost post = discussPostService.findDiscussPostById(discussPostId);
        model.addAttribute("post", post);
        // 作者
        User user = userService.selectUserById(Integer.valueOf(post.getUserId()));
        model.addAttribute("user", user);
        //点赞数量
        long likeCount = likeService.findEntityLikeCount(CommunityConstant.ENTITY_TYPE_POST, post.getId());
        model.addAttribute("likeCount", likeCount);
        // 点赞状态
        int likeStatus = hostHolder.getUser() == null ? 0 : likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_POST, post.getId());
        model.addAttribute("likeStatus", likeStatus);
        //评论分页信息
        page.setSize(5);
        page.setDesc("create_time");

        // 评论: 给帖子的评论
        // 回复: 给评论的评论
        // 评论列表
        List<Comment> commentsList = commentService.findCommentsByEntity(page, ENTITY_TYPE_POST, post.getId());
        log.info("page:" + page.getTotal() + " - " + page.getPages());
        // 封装page对象导PageDTO中，后面可以优化
        PageDTO pageDTO = new PageDTO(page);
        pageDTO = pageDTO.pageDTO();
        model.addAttribute("pagedto", pageDTO);
        pageDTO.setPath("/discuss-post/detail/" + discussPostId);
        log.info("封装Page：" + pageDTO);
        model.addAttribute("page", page);
        //重置page,回复无需分页
        page = new Page();
        page.setSize(Integer.MAX_VALUE);

        // 评论VO列表
        List<Map<String, Object>> commentVoList = new ArrayList<>();
        if (commentsList != null) {
            for (Comment comment : commentsList) {
                //评论VO
                Map<String, Object> commentVo = new HashMap<>();
                //评论
                commentVo.put("comment", comment);
                //评论用户
                commentVo.put("user", userService.selectUserById(comment.getUserId()));
                // 点赞数量
                likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeCount", likeCount);
                // 点赞状态
                likeStatus = hostHolder.getUser() == null ? 0 :
                        likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeStatus", likeStatus);
                // 回复列表 ENTITY_TYPE_COMMENT=2表示对评论的评论 根据评论的ID查找评论的回复
                List<Comment> replyList = commentService.findCommentsByEntity(page,
                        ENTITY_TYPE_COMMENT, comment.getId());
                // 回复VO列表 把查到的回复列表进行遍历 得到回复的用户信息，以及回复的目标，若目标为0，表示回复的是评论
                List<Map<String, Object>> replyVoList = new ArrayList<>();
                if (replyList != null) {
                    for (Comment reply : replyList) {
                        Map<String, Object> replyVo = new HashMap<>();
                        // 回复
                        replyVo.put("reply", reply);
                        // 作者
                        replyVo.put("user", userService.selectUserById(reply.getUserId()));
                        // 点赞数量
                        likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.put("likeCount", likeCount);
                        // 点赞状态
                        likeStatus = hostHolder.getUser() == null ? 0 :
                                likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.put("likeStatus", likeStatus);
                        // 回复目标
                        User target = reply.getTargetId() == 0 ? null : userService.selectUserById(reply.getTargetId());
                        replyVo.put("target", target);
                        replyVoList.add(replyVo);
                    }
                }
                commentVo.put("replys", replyVoList);
                // 回复数量
                commentVo.put("replyCount", page.getTotal());

                commentVoList.add(commentVo);
            }
        }
        model.addAttribute("comments", commentVoList);
        return "/site/discuss-detail";
    }

    @PostMapping("/top")
    public @ResponseBody String setTop(Integer postId) {
       discussPostService.modifyDiscussByType(postId, 1);
       //触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(postId);
        eventProducer.fireEvent(event);

        return CommonUtils.getJSON(0);
    }
    @PostMapping("/wonderful")
    public @ResponseBody String setWonderful(Integer postId) {
       discussPostService.modifyDiscussByStatus(postId, 1);
       //触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(postId);
        eventProducer.fireEvent(event);
        return CommonUtils.getJSON(0);
    }
    @PostMapping("/delete")
    public @ResponseBody String setDelete(Integer postId) {
       discussPostService.modifyDiscussByStatus(postId, 2);
       //触发删帖事件
        Event event = new Event()
                .setEntityId(postId)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setTopic(TOPIC_DELETE);

        eventProducer.fireEvent(event);

        return CommonUtils.getJSON(0);
    }

    /**
     * 根据用户id查询对应的帖子
     * @return
     */
    @GetMapping("/profile/my-post/{userid}")
    public String getMyPost(@PathVariable("userid")Integer userId, Page<DiscussPost> page, Model model){
        page.setSize(8);
        page.setDesc("type","create_time");
        User user = userService.selectUserById(userId);
        model.addAttribute("user", user);
        List<DiscussPost> posts = discussPostService.findDiscussPostByUserId(page, userId);
        // 将文章信息 以及 用户信息 存到Map中，然后循环遍历discussPosts中的文章信息
        List<Map<String,Object>> lists = new ArrayList<>();
        if (posts != null){
            for (DiscussPost discussPost : posts){
                Map<String,Object> map = new HashMap<>();
                map.put("post",discussPost);
                map.put("user", user);
                //点赞数
                long likeCount = likeService.findEntityLikeCount(1, discussPost.getId());
                map.put("likeCount", likeCount);
                lists.add(map);
            }
        }
        // 封装page对象导PageDTO中，后面可以优化
        PageDTO pageDTO = new PageDTO(page);
        pageDTO = pageDTO.pageDTO();
        pageDTO.setPath("/profile/my-post/" + userId);
        model.addAttribute("pagedto", pageDTO);
        log.info("封装Page：" + pageDTO);
        model.addAttribute("page", page);
        model.addAttribute("discussPosts", lists);
        return "/site/my-post";
    }
}
